package com.ep.thirdPlatformProject.workWx;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.config.WxCpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import me.chanjar.weixin.cp.message.WxCpMessageHandler;
import me.chanjar.weixin.cp.message.WxCpMessageRouter;
import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil;

import java.io.IOException;

public class WxCpServlet extends HttpServlet {

    protected WxCpConfigStorage config;
    protected WxCpService wxCpService;
    protected WxCpMessageRouter wxCpMessageRouter;

    @Override
    public void init() throws ServletException {
        super.init();
        config = new WxCpDefaultConfigImpl();
        config.getCorpId();      // 设置微信企业号的appid
        config.getCorpSecret();  // 设置微信企业号的app corpSecret
        config.getAgentId();     // 设置微信企业号应用ID
        config.getToken();       // 设置微信企业号应用的token
        config.getAesKey();      // 设置微信企业号应用的EncodingAESKey

        wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);

        WxCpMessageHandler handler = (wxCpXmlMessage, map, wxCpService, wxSessionManager) -> WxCpXmlOutMessage
                .TEXT()
                .content("测试加密消息")
                .fromUser(wxCpXmlMessage.getToUserName())
                .toUser(wxCpXmlMessage.getFromUserName())
                .build();

        wxCpMessageRouter = new WxCpMessageRouter(wxCpService);
        wxCpMessageRouter
                .rule()
                .async(false)
                .content("哈哈") // 拦截内容为“哈哈”的消息
                .handler(handler)
                .end();
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);

        String msgSignature = request.getParameter("msg_signature");
        String nonce = request.getParameter("nonce");
        String timestamp = request.getParameter("timestamp");
        String echoStr = request.getParameter("echostr");

        if (StrUtil.isNotBlank(echoStr)) {
            if (!wxCpService.checkSignature(msgSignature, timestamp, nonce, echoStr)) {
                // 消息签名不正确，说明不是公众平台发过来的消息
                response.getWriter().println("非法请求");
                return;
            }
            WxCpCryptUtil cryptUtil = new WxCpCryptUtil(config);
            String plainText = cryptUtil.decrypt(echoStr);
            // 说明是一个仅仅用来验证的请求，回显echoStr
            response.getWriter().println(plainText);
            return;
        }

        WxCpXmlMessage inMessage = WxCpXmlMessage.fromEncryptedXml(request.getInputStream(), config, timestamp, nonce, msgSignature);
        WxCpXmlOutMessage outMessage = wxCpMessageRouter.route(inMessage);
        if (outMessage != null) {
            response.getWriter().write(outMessage.toEncryptedXml(config));
        }

        return;
    }

}